#!/bin/sh


if [ $# -lt 1 ]; then
	echo "Usage: chroot.sh [dir_to_rootfs]"
fi

ROOTFS=$1

if [ -d $ROOTFS/proc/1 ]; then
	MOUNT=0
else
	MOUNT=1
fi

if [ $UID -eq 0 ] ; then
	SUDO=""
else
	SUDO="sudo"
fi

DISK=`mount | grep "/media/disk" | cut -d " " -f 1`

if [ $MOUNT = 1 ]; then
	echo "Mount file system"
	$SUDO mount proc -t proc $ROOTFS/proc
	$SUDO mount sys -t sysfs $ROOTFS/sys
	$SUDO mount --bind /dev $ROOTFS/dev
	$SUDO mount $DISK $ROOTFS/media/disk
fi


$SUDO chroot $ROOTFS /bin/bash -l

UNMOUNT=`ps aux | grep "chroot $ROOTFS" | grep -v grep | wc -l`

if [ $UNMOUNT = 0 ]; then
	echo "Umount file system"
	$SUDO umount $ROOTFS/media/disk
	$SUDO umount $ROOTFS/dev
	$SUDO umount $ROOTFS/sys
	$SUDO umount $ROOTFS/proc
fi

